package com.easyto.filter;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;


/**
 * 自定义添加请求头
 */
@WebFilter(urlPatterns = "/*")
@Order(Integer.MIN_VALUE)
public class AddNameFilter implements Filter {

    public static final LoadingCache<String, String> CACHE = CacheBuilder
            .newBuilder()
            .initialCapacity(20)
            // 最大容量为 100 超过容量有对应的淘汰机制，下文详述
            .maximumSize(100)
            // 缓存项写入后多久过期，下文详述
            .expireAfterWrite(1, TimeUnit.HOURS)
            // 缓存写入后多久自动刷新一次，下文详述
            .refreshAfterWrite(30, TimeUnit.MINUTES)
            // 创建一个 CacheLoader，load 表示缓存不存在的时候加载到缓存并返回
            .build(new CacheLoader<String, String>() {
                // 加载缓存数据的方法
                @Override
                public String load(String key) {
                    System.out.println(">>>>>>>>>> 访问了： >>>>>>>>>>  " + key);
                    if ("1111".equals(key)) {
                        return "zhangsan";
                    }

                    if ("2222".equals(key)) {
                        return "lisi";
                    }
                    if ("3333".equals(key)) {
                        return "wangwu";
                    }
                    return null;
                }
            });


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        filterChain.doFilter(new HttpServletRequestWrapper(request) {

            @Override
            public Enumeration<String> getHeaders(String name) {
                List<String> allHeaders = new ArrayList<>();

                // 添加原始请求头
                Enumeration<String> originalHeaders = super.getHeaders(name);
                if (originalHeaders != null) {
                    while (originalHeaders.hasMoreElements()) {
                        allHeaders.add(originalHeaders.nextElement());
                    }
                }

                // 添加自定义请求头
                if (CollectionUtils.isEmpty(allHeaders) && "uname".equals(name)) {
                    String userId = "1111";

                    try {
                        String userName = CACHE.get(userId);
                        ArrayList<String> names = Lists.newArrayList(userName);
                        allHeaders.addAll(names);
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }

                }
                return Collections.enumeration(allHeaders);
            }

        }, servletResponse);
    }

    @Override
    public void destroy() {
    }
}
